﻿#include "DialogShieldingEfficiency.h"
#include "ui_DialogShieldingEfficiency.h"

#include "AnimationSettingData.h"
#include "DataChosenListDialog.h"
#include <QIntValidator>
#include "IdaWidgetHelper.h"
#include "IdaDialogMsg.h"
#include <QListView>
#include <QDebug>

namespace pst
{
    DialogShieldingEfficiency::DialogShieldingEfficiency(QWidget* parent)
        : IdaDialogFrame(parent), ui(new Ui::DialogShieldingEfficiency())
    {
        ui->setupUi(this);

        setWindowTitle(QStringLiteral("屏蔽效能"));
        IdaWidgetHelperInstance->setMainButtonStyle(ui->pushButton_confirm); // 将确定设置为主按钮

        ui->textEdit_PluralForm->setStyleSheet("QTextEdit { border: none; }");
        ui->textEdit_AmplitudeForm->setStyleSheet("QTextEdit { border: none; }");
        ui->textEdit_PluralForm->setFixedHeight(100);
        ui->textEdit_AmplitudeForm->setFixedHeight(100);

        ui->pushButton_TotalElectricField->setIcon(QIcon(":/rc/apostrophe.png"));
        ui->pushButton_TotalElectricField->setStyleSheet("QPushButton { text-align: center; }");

        ui->pushButton_PluralForm->setIcon(QIcon(":/rc/apostrophe.png"));
        ui->pushButton_PluralForm->setStyleSheet("QPushButton { text-align: center; }");

        ui->pushButton_AmplitudeForm->setIcon(QIcon(":/rc/apostrophe.png"));
        ui->pushButton_AmplitudeForm->setStyleSheet("QPushButton { text-align: center; }");

        // HTML 设置公式内容
        QString formula = R"(
        <html>
            <body>
                <div class="formula" style="line-height: 8px;">
                    <p style="margin: 0;">E<sub>total</sub> = sqrt(|E<sub>x</sub>|² + |E<sub>y</sub>|² + |E<sub>z</sub>|²)</p>
                </div>
            </body>
        </html>
    )";

        ui->label_formula1->setText(formula);
        ui->label_formula1->setStyleSheet("QLabel { font-size: 12px; font-family: Times New Roman;}");
        ui->label_formula1->setAlignment(Qt::AlignCenter);

        QString formula1 = R"(
        <html>
            <body>
                <div class="formula" style="line-height: 8px;">                  
                    <p style="margin: 0;">屏蔽效能 = -20lg(E<sub>total</sub> / E<sub>0</sub>)</p>
                </div>
            </body>
        </html>
    )";

        ui->label_formula2->setText(formula1);
        ui->label_formula2->setStyleSheet("QLabel { font-size: 12px; font-family: Times New Roman;}");
        ui->label_formula2->setAlignment(Qt::AlignCenter);

        ui->doubleSpinBox_PlaneWaveAmplitude->setDecimals(9);
        ui->doubleSpinBox_PlaneWaveAmplitude->setMinimum(1e-9);
        ui->doubleSpinBox_PlaneWaveAmplitude->setMaximum(1e9);
        ui->label_PluralForm->setText(QStringLiteral("选择复数形式的电场分量曲线\nre(Ex)/im(Ex)/re(Ey)im(Ey)/re(Ez)im(Ez)"));
        ui->label_AmplitudeForm->setText(QStringLiteral("选择幅度形式的电场分量曲线\narg(Ex)/arg(Ey)/arg(Ez)"));

        on_radioButton_TotalElectricField_toggled(true);
    }

    DialogShieldingEfficiency::~DialogShieldingEfficiency()
    {
        delete ui;
    }

    void DialogShieldingEfficiency::setCurveNameList(const QList<QString>& curveNameList)
    {
        m_curveNameList = curveNameList;
        m_model.setStringList(m_curveNameList);
    }

    void DialogShieldingEfficiency::setInit(QStringList& params)
    {
        if (params.at(0) != "1")
            return;
        params.removeFirst();
        double e0 = params.back().toLong();
        params.removeLast();

        QString content = params.join("\n");
        switch (params.size())
        {
        case 1:
            ui->radioButton_TotalElectricField->setChecked(true);
            ui->radioButton_PluralForm->setChecked(false);
            ui->radioButton_AmplitudeForm->setChecked(false);
            on_radioButton_TotalElectricField_toggled(true);
            ui->lineEdit_TotalElectricField->setText(content);
            ui->doubleSpinBox_PlaneWaveAmplitude->setValue(e0);
            m_isTotalElectricFieldPushButtonClicked = true;

            m_selectedIndexsTotalElectricField.clear();
            foreach (const QString& str, params)
            {
                int index = m_curveNameList.indexOf(str);
                if (index != -1)
                    m_selectedIndexsTotalElectricField.append(index);
            }
            break;
        case 6:
            ui->radioButton_TotalElectricField->setChecked(false);
            ui->radioButton_PluralForm->setChecked(true);
            ui->radioButton_AmplitudeForm->setChecked(false);
            on_radioButton_PluralForm_toggled(true);
            ui->textEdit_PluralForm->setPlainText(content);
            ui->doubleSpinBox_PlaneWaveAmplitude->setValue(e0);
            m_isPluralFormPushButtonClicked = true;

            m_selectedIndexsPluralForm.clear();
            foreach (const QString& str, params)
            {
                int index = m_curveNameList.indexOf(str);
                if (index != -1)
                    m_selectedIndexsPluralForm.append(index);
            }
            break;
        case 3:
            ui->radioButton_TotalElectricField->setChecked(false);
            ui->radioButton_PluralForm->setChecked(false);
            ui->radioButton_AmplitudeForm->setChecked(true);
            on_radioButton_AmplitudeForm_toggled(true);
            ui->textEdit_AmplitudeForm->setPlainText(content);
            ui->doubleSpinBox_PlaneWaveAmplitude->setValue(e0);
            m_isAmplitudeFormPushButtonClicked = true;

            m_selectedIndexsAmplitudeForm.clear();
            foreach (const QString& str, params)
            {
                int index = m_curveNameList.indexOf(str);
                if (index != -1)
                    m_selectedIndexsAmplitudeForm.append(index);
            }
            break;
        default:
            break;
        }

        slot_sentChosenDataIds(createSelectedIndexes(params));
    }

    void DialogShieldingEfficiency::on_pushButton_confirm_clicked()
    {
        if (ui->radioButton_TotalElectricField->isChecked() && m_selectedIndexsTotalElectricField.isEmpty())
        {
            auto _text = QString("未选择任何曲线，请选择曲线！");
            auto _res = IdaDialogMsg::showDialog(nullptr, _text, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            return;
        }
        else if (ui->radioButton_PluralForm->isChecked() && m_selectedIndexsPluralForm.count() != 6)
        {
            auto _text = QString("复数形式电场曲线须选择六条曲线，请选择曲线！");
            auto _res = IdaDialogMsg::showDialog(nullptr, _text, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            return;
        }
        else if (ui->radioButton_AmplitudeForm->isChecked() && m_selectedIndexsAmplitudeForm.count() != 3)
        {
            auto _text = QString("幅相形式电场曲线须选择三条曲线，请选择曲线！");
            auto _res = IdaDialogMsg::showDialog(nullptr, _text, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            return;
        }

        auto _value = ui->doubleSpinBox_PlaneWaveAmplitude->value();
        if (qFuzzyCompare(_value, 0.0000000000))
        {
            auto _text = QString("输入无效，请输入非0正实数！");
            auto _res = IdaDialogMsg::showDialog(nullptr, _text, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            return;
        }
        if (ui->radioButton_TotalElectricField->isChecked())
            emit signal_computeEffectiveness(ui->lineEdit_TotalElectricField->text(), ui->doubleSpinBox_PlaneWaveAmplitude->value());
        else if (ui->radioButton_PluralForm->isChecked())
            emit signal_computeEffectiveness(ui->textEdit_PluralForm->toPlainText(), ui->doubleSpinBox_PlaneWaveAmplitude->value());
        else if (ui->radioButton_AmplitudeForm->isChecked())
            emit signal_computeEffectiveness(ui->textEdit_AmplitudeForm->toPlainText(), ui->doubleSpinBox_PlaneWaveAmplitude->value());
        this->close();
    }

    void DialogShieldingEfficiency::on_pushButton_cancel_clicked()
    {
        this->close();
    }

    void DialogShieldingEfficiency::on_radioButton_TotalElectricField_toggled(bool checked)
    {
        ui->lineEdit_TotalElectricField->setEnabled(checked);
        ui->pushButton_TotalElectricField->setEnabled(checked);

        ui->pushButton_PluralForm->setEnabled(!checked);
        ui->textEdit_PluralForm->setEnabled(!checked);

        ui->pushButton_AmplitudeForm->setEnabled(!checked);
        ui->textEdit_AmplitudeForm->setEnabled(!checked);
    }
    void DialogShieldingEfficiency::on_radioButton_PluralForm_toggled(bool checked)
    {
        ui->lineEdit_TotalElectricField->setEnabled(!checked);
        ui->pushButton_TotalElectricField->setEnabled(!checked);

        ui->pushButton_PluralForm->setEnabled(checked);
        ui->textEdit_PluralForm->setEnabled(checked);

        ui->pushButton_AmplitudeForm->setEnabled(!checked);
        ui->textEdit_AmplitudeForm->setEnabled(!checked);
    }
    void DialogShieldingEfficiency::on_radioButton_AmplitudeForm_toggled(bool checked)
    {
        ui->lineEdit_TotalElectricField->setEnabled(!checked);
        ui->pushButton_TotalElectricField->setEnabled(!checked);

        ui->pushButton_PluralForm->setEnabled(!checked);
        ui->textEdit_PluralForm->setEnabled(!checked);

        ui->pushButton_AmplitudeForm->setEnabled(checked);
        ui->textEdit_AmplitudeForm->setEnabled(checked);
    }

    void DialogShieldingEfficiency::slot_sentChosenDataIds(const QModelIndexList& chosenID)
    {
        if (ui->radioButton_TotalElectricField->isChecked())
            m_selectedIndexsTotalElectricField.clear();
        else if (ui->radioButton_PluralForm->isChecked())
            m_selectedIndexsPluralForm.clear();
        else if (ui->radioButton_AmplitudeForm->isChecked())
            m_selectedIndexsAmplitudeForm.clear();
        auto count = chosenID.count();
        QString strText{};
        for (int i = 0; i < count; ++i)
        {
            auto chosenData = chosenID.at(i);
            if (chosenData.isValid())
            {
                auto str = chosenData.data().toString();
                strText += str + "\n";

                auto index = chosenID.at(i).row();
                if (ui->radioButton_TotalElectricField->isChecked())
                    m_selectedIndexsTotalElectricField.append(index);
                else if (ui->radioButton_PluralForm->isChecked())
                    m_selectedIndexsPluralForm.append(index);
                else if (ui->radioButton_AmplitudeForm->isChecked())
                    m_selectedIndexsAmplitudeForm.append(index);
            }
        }

        if (m_isTotalElectricFieldPushButtonClicked)
        {
            ui->lineEdit_TotalElectricField->setText(strText);
            if (!strText.isEmpty())
                IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_TotalElectricField, true, Qt::blue);
            else
                IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_TotalElectricField, false, Qt::white);
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_PluralForm, false, Qt::white);
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_AmplitudeForm, false, Qt::white);
        }
        if (m_isPluralFormPushButtonClicked)
        {
            ui->textEdit_PluralForm->setText(strText);
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_TotalElectricField, false, Qt::white);
            if (!strText.isEmpty())
                IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_PluralForm, true, Qt::blue);
            else
                IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_PluralForm, false, Qt::white);
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_AmplitudeForm, false, Qt::white);
        }
        if (m_isAmplitudeFormPushButtonClicked)
        {
            ui->textEdit_AmplitudeForm->setText(strText);
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_TotalElectricField, false, Qt::white);
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_PluralForm, false, Qt::white);
            if (!strText.isEmpty())
                IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_AmplitudeForm, true, Qt::blue);
            else
                IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_AmplitudeForm, false, Qt::white);
        }
    }

    void DialogShieldingEfficiency::on_pushButton_TotalElectricField_clicked()
    {
        m_isTotalElectricFieldPushButtonClicked = true;
        m_isPluralFormPushButtonClicked = false;
        m_isAmplitudeFormPushButtonClicked = false;
        openDataChosenListDialog(false);
    }
    void DialogShieldingEfficiency::on_pushButton_PluralForm_clicked()
    {
        m_isTotalElectricFieldPushButtonClicked = false;
        m_isPluralFormPushButtonClicked = true;
        m_isAmplitudeFormPushButtonClicked = false;
        openDataChosenListDialog(true);
    }
    void DialogShieldingEfficiency::on_pushButton_AmplitudeForm_clicked()
    {
        m_isTotalElectricFieldPushButtonClicked = false;
        m_isPluralFormPushButtonClicked = false;
        m_isAmplitudeFormPushButtonClicked = true;
        openDataChosenListDialog(true);
    }

    void DialogShieldingEfficiency::openDataChosenListDialog(bool isMultiSelect)
    {
        m_dataChosenListDialog = new DataChosenListDialog();
        m_dataChosenListDialog->setFixedSize(300, 280);
        // m_dataChosenListDialog->moveToCenter();
        m_dataChosenListDialog->setData(m_curveNameList);
        m_dataChosenListDialog->setMultipleSelected(isMultiSelect);
        m_dataChosenListDialog->updateUI();
        m_dataChosenListDialog->showWindow();
        if (ui->radioButton_TotalElectricField->isChecked())
            m_dataChosenListDialog->setSelctedIndexs(m_selectedIndexsTotalElectricField);
        else if (ui->radioButton_PluralForm->isChecked())
            m_dataChosenListDialog->setSelctedIndexs(m_selectedIndexsPluralForm);
        else if (ui->radioButton_AmplitudeForm->isChecked())
            m_dataChosenListDialog->setSelctedIndexs(m_selectedIndexsAmplitudeForm);

        connect(m_dataChosenListDialog,
                &DataChosenListDialog::signal_sentChosenDataIds,
                this, &DialogShieldingEfficiency::slot_sentChosenDataIds);
    }

    QModelIndexList DialogShieldingEfficiency::createSelectedIndexes(const QStringList& params) {
        QModelIndexList selectedIndexes;

        foreach(const QString & param, params) {
            int row = m_curveNameList.indexOf(param);
            if (row != -1) {
                // 使用成员模型m_model创建索引，确保索引与模型生命周期一致
                QModelIndex index = m_model.index(row, 0);
                if (index.isValid()) {
                    selectedIndexes.append(index);
                }
            }
        }
        return selectedIndexes;
    }
} // namespace pst
